# -*- coding: UTF-8 -*-
"""
@Project ：swift-forge-engine 
@File    ：login_log_crud
@IDE     ：PyCharm 
@Author  ：Tony
@Date    ：2025/2/21 9:53 
@Des     ：
"""
from sqlalchemy import Select, select, desc, and_, asc
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus

from App.app.admin.models.login_log import LoginLog
from App.app.admin.schemas.login_log_schema import CreateLoginLogParam
from App.common.order_by import apply_dynamic_sort


class CRUDLoginLog(CRUDPlus[LoginLog]):
    async def get_list(
            self, username: str | None = None, status: str | None = None, ip: str | None = None,
            sort_field: str | None = None, sort_order: str | None = None) -> Select:
        """
        获取登录日志列表

        :param sort_order:
        :param sort_field:
        :param username:
        :param status:
        :param ip:
        :return:
        """
        stmt = (
            select(self.model)
        )
        where_list = []
        if status:
            where_list.append(self.model.status == int(status))
        if username:
            where_list.append(self.model.username.like(f'%{username}%'))
        if ip:
            where_list.append(self.model.ip.like(f'%{ip}%'))
        if where_list:
            stmt = stmt.where(and_(*where_list))
        stmt = apply_dynamic_sort(stmt, self.model, sort_field=sort_field, sort_order=sort_order)
        return stmt

    async def create(self, db: AsyncSession, obj_in: CreateLoginLogParam) -> None:
        """
        创建登录日志

        :param db:
        :param obj_in:
        :return:
        """
        await self.create_model(db, obj_in, commit=True)

    async def delete(self, db: AsyncSession, pk: list[int]) -> int:
        """
        删除登录日志

        :param db:
        :param pk:
        :return:
        """
        return await self.delete_model_by_column(db, allow_multiple=True, id__in=pk)

    async def delete_all(self, db: AsyncSession) -> int:
        """
        删除所有登录日志

        :param db:
        :return:
        """
        return await self.delete_model_by_column(db, allow_multiple=True)


LoginLogDao: CRUDLoginLog = CRUDLoginLog(LoginLog)
